package org.dxw.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.dxw.common.excep.BusinessExcep;
import org.dxw.common.enums.GlobalResultEnum;
import org.dxw.resp.BaseResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description:
 * @author: dxw
 * @create: 2022-04-04 23:24
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionAspect {


    /**
     * 处理业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BusinessExcep.class)
    public BaseResponse businessExcepHandler(BusinessExcep ex) {
        log.warn("发生了业务异常：", ex);
        return BaseResponse.error(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse paramExcepHandler(MethodArgumentNotValidException ex) {
        log.warn(ex.getMessage(), ex);
        String message = ex.getBindingResult().getFieldError().getDefaultMessage();
        return BaseResponse.error(GlobalResultEnum.PARAM_ERR);
    }

    /**
     * 异常兜底
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResponse errorHandler(Exception ex) {
        log.warn(ex.getMessage(), ex);
        return BaseResponse.error(GlobalResultEnum.ERROR);
    }


}